/**
 * Crazy Table Tool
 *  License by CrazyYi.
 *  v1.0.0
 *
 *
 */
layui.define(['table', 'jquery', 'form', 'layer', 'laydate'], function (exports) {
    const MOD_NAME = 'crazyTool',
        TIME_FORMAT = 'yyyy-MM-dd HH:mm:ss'

    /**
     * 工具
     * @type {{
     *      getEachTds: (function(*): Array),
     *      compare: compare,
     *      uniqueObjArray: uniqueObjArray,
     *      formatTime: formatTime,
     *      toObjects: (function(*=): Array),
     *      isBlank: (function(*=): boolean),
     *      getFieldArray: (function(*, *=, *=): Array),
     *      dayTime: (function(*=): {start: number, end: number}),
     *      inArrayOrSame: (function(*=, *=): number),
     *      getKeyByValue: getKeyByValue,
     *      timeFormat: (function(*, *=): *),
     *      isNotBlank: (function(*=): boolean),
     *      defaultString: (function(*=, *): string),
     *      getSameArray: (function(*, *): Array),
     *      toObject: toObject,
     *      isIntNum: (function(*=): boolean),
     *      toLayuiForm: (function(*=, *, *): (any | string)),
     *      mouseover: mouseover,
     *      }}
     */
    const crazyTool = {
        isBlank: (str) => {
            return str === undefined || str === null || /^\s*$/.test(str)
        },
        isNotBlank: (str) => {
            return !crazyTool.isBlank(str)
        },
        defaultString: function (str, defaultStr) {
            return crazyTool.isBlank(str) ? (defaultStr ? defaultStr : "") : str
        },
        formatTime: (millisecond) => {
            // 将毫秒格式化为 可读的 字符串
            if (!Number.isInteger(millisecond)) {
                return millisecond
            }
            let second = millisecond / 1000

            if (second < 60) {
                return (second) + "秒"
            } else if (second / 60 < 60) {
                return Math.floor((second / 60)) + "分" + Math.floor((second % 60)) + "秒"
            } else if (second / 60 / 60 < 24) {
                return Math.floor((second / 60 / 60)) + "时" + Math.floor((second / 60 % 60)) + "分" + Math.floor((second % 60)) + "秒"
            } else {
                return Math.floor((second / 86400)) + "天" + Math.floor((second % 86400 / 60 / 60)) + "时" +
                    Math.floor((second % 86400 / 60 % 60)) + "分" + Math.floor((second % 60)) + "秒"
            }
            return millisecond
        },

        /**
         * 获取同一个field 的所有值（默认去掉重复值）
         * @param datas: 二位数组，保存的是table 的所有数据
         * @param field
         * @param isUnique
         * @returns {Array}
         */
        getFieldArray: function (datas, field, isUnique) {
            isUnique = isUnique || true;
            let newArr = [];
            for (let i in datas) {
                if (datas.hasOwnProperty(i)) {
                    if (datas[i].hasOwnProperty(field)) {
                        let curV = datas[i][field];
                        if (!!curV) {
                            if (!isUnique) {
                                newArr.push(curV);
                            } else {
                                if (!newArr.includes(curV)) {
                                    newArr.push(curV);
                                }
                            }
                        }
                    }
                }
            }

            $.each(newArr, function (i, item) {
                newArr[i] = {key: item, value: item}
            });

            return newArr;
        },

        compare: function (str1, str2, strict) {
            strict = strict || false;
            if (strict) {
                return str1 === str2;
            } else {
                return (str1 + '') === (str2 + '');
            }
        },
        toObject: function (item) {
            if (item.constructor === Object) {
                return item;
            } else {
                return {key: item, value: item};
            }
        },
        toObjects: function (list) {
            let newList = [];
            $.each(list, function (i, item) {
                let newItem = crazyTool.toObject(item);
                newList.push(newItem)
            })
            return newList;
        },
        /**
         * 将时间戳转变为时间格式
         * @param currDate
         * @param format
         * @returns {*}
         */
        timeFormat: function (currDate, format) {
            format = format || TIME_FORMAT;
            return currDate;
        },

        /**
         * 数组&对象数组去重
         * @param arr
         * @param type
         * @returns {Array|*}
         */
        uniqueObjArray: function (arr, type) {
            let newArr = [];
            let tArr = [];
            if (arr.length === 0) {
                return arr;
            } else {
                if (type) {
                    for (let i = 0; i < arr.length; i++) {
                        if (!tArr[arr[i][type]]) {
                            newArr.push(arr[i]);
                            tArr[arr[i][type]] = true;
                        }
                    }
                    return newArr;
                } else {
                    for (let i = 0; i < arr.length; i++) {
                        if (!tArr[arr[i]]) {
                            newArr.push(arr[i]);
                            tArr[arr[i]] = true;
                        }
                    }
                    return newArr;
                }
            }
        },
        /**
         * 合并数组取相同项
         * @param array1
         * @param array2
         * @returns {Array}
         */
        getSameArray: function (array1, array2) {
            let newArr = [];
            for (let i = 0; i < array1.length; i++) {
                for (let j = 0; j < array2.length; j++) {
                    if (array2[j] === array1[i]) {
                        newArr.push(array2[j]);
                    }
                }
            }
            return newArr;
        },
        /**
         * 获取同一个field 的所有值（默认去掉重复值）
         * @param field
         * @param isUnique
         * @returns {Array}
         */

        /**
         * 将缓存中保存的JSON 数据 转换成 layui form 可用的 处理checkbox
         *
         * @param array
         * @param name
         * @param type
         * @returns {any | string}
         */
        toLayuiForm: function (array, name, type) {
            let form_val = JSON.stringify(array);
            form_val = JSON.parse(form_val);
            console.log('form_value before', form_val);
            if ((type === "checkbox" || type === 'input') && $.isArray(form_val[name])) {
                $.each(form_val[name], function (i, value) {
                    form_val[name + "[" + value + "]"] = true;
                });
                // delete form_val[name];
            }
            if (type === 'input' && !$.isArray(form_val[name])) {
                form_val[name + "[" + form_val[name] + "]"] = true;
            }
            // console.log('toLayuiForm', form_val);
            return form_val;
        },
        /**
         * 遍历行获取本地列集合 return tdsArray[]
         * @param tds
         * @returns {Array}
         */
        getEachTds: function (tds) {
            let tdsText = [],
                tdsArray = [];
            tds.each(function (i, td) {
                tdsText.push($.trim(td.innerText))
            });
            tdsText = crazyTool.uniqueObjArray(tdsText);
            $.each(tdsText, function (i, item) {
                tdsArray.push({'key': item, 'value': item})
            });
            return tdsArray;
        },
        /**
         * 输入一个日期，获取该日期所在天的起点和终点时间戳
         * @param currDate
         * @returns {{start: number, end: number}}
         */
        dayTime: function (currDate) {
            currDate = new Date(currDate);
            let y = currDate.getFullYear();
            let m = currDate.getMonth();
            let d = currDate.getDate();

            let timeS = new Date(y, m, d, 0, 0, 0);
            let timeE = new Date(y, m, d, 23, 59, 59);
            return {start: timeS.getTime() / 1000, end: timeE.getTime() / 1000};
        },
        /**
         * 在数组中查找某个值，返回所在位置。下标从0开始，没找到返回-1
         * @param value
         * @param array
         * @returns {number}
         */
        inArrayOrSame: function (value, array) {
            let found = -1;
            if ($.isArray(array)) {
                //过滤值=数组 inArray 复选框
                if (array && array.length > 0) {
                    $.each(array, function (j, v) {
                        if (crazyTool.compare(v, value, false)) {
                            found = j;
                            return false; // break, 找到，退出
                        }
                    });
                }
            } else {
                //过滤值=字符串 indexOf 单选框 输入框
                if (crazyTool.compare(array, value, false)) {
                    found = 0;
                }
            }
            return found;
        },

        isIntNum: function (val) {
            let regPos = /^\d+$/; // 非负整数
            let regNeg = /^\-[1-9][0-9]*$/; // 负整数
            let res = (regPos.test(val) || regNeg.test(val));

            // console.log('isIntNum in=', val, 'result=', res);
            return res;
        },

        /**
         * 通过value，在数据字典dict中查找对应的key
         * @param dict
         * @param value
         * @returns {boolean}
         */
        getKeyByValue: function (dict, value) {
            let curK = '';
            if (dict.constructor === Array) {
                $.each(dict, function (i, item) {
                    if (item.hasOwnProperty('key') && item.hasOwnProperty('value')) {
                        if (crazyTool.compare(item.value, value, false)) {
                            curK = item.key;
                            return false; // break
                        }
                    }
                });
                return curK;
            } else {
                return false;
            }
        },
        /**
         * 悬停后提示
         * @param _elem
         * @param title
         * @param option
         */
        mouseover: function (_elem, title, option) {
            let cell = $(_elem);
            let opt = {
                title: undefined,
                color: "#7c7c7c",   // tips 背景色
                direct: 3, // 显示的方向，支持上右下左四个方向，通过1-4进行方向设定
                duration: 2000, // 自动关闭时间，默认2000ms，单位是ms。0表示不关闭
                delay: 500, // 鼠标悬停多久时间后进入tips
            };
            $.extend(opt, option);

            let lId;
            const tips = (cell, opt) => {
                lId = layer.tips(title, cell, {tips: [3, opt.color], time: opt.duration})
            };

            let outTimer, hoverTimer;
            cell.hover(function () {
                clearTimeout(outTimer);
                hoverTimer = setTimeout(function () {tips(cell, opt)}, opt.delay);
            }, function () {
                clearTimeout(hoverTimer);
                outTimer = setTimeout(function () { layer.close(lId) }, opt.delay);
            });
        },

    };


    //输出接口
    exports(MOD_NAME, crazyTool);
});